﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Xml.Linq;
using TallyJ1Reporter;
using TallyJ1Reporter.Properties;

namespace TallyJ1Reporter.XmlSource
{
	public class ImportFromXml
	{
		public ImportFromXml()
		{
			ErrorMessages = new List<string>();
		}

		public string FilePath
		{
			get;
			private set;
		}

		public XElement ImportedElectionXml
		{
			get;
			private set;
		}

		public List<string> ErrorMessages
		{
			get;
			private set;
		}

		public bool ImportSuccessful
		{
			get;
			private set;
		}

		public bool SourceExists
		{
			get;
			set;
		}

		public ImportFromXml AttachTo(string filePath)
		{
			SourceExists = File.Exists(filePath);
			if (SourceExists)
			{
				FilePath = filePath;
			}
			else
			{
				ErrorMessages.Add(string.Format(Resources.FileNotFound, filePath));
				FilePath = string.Empty;
			}
			return this;
		}

		public ImportFromXml ImportData()
		{
			if (SourceExists)
			{
				try
				{
					StreamReader file = null;

					var attempts = 10;
					do
					{
						attempts--;
						try
						{
							file = File.OpenText(FilePath);
						}
						catch (Exception)
						{
							if (attempts == 0)
							{
								throw;
							}
							Debugger.Log(0, "Glen", "Waiting for file to save");
							Thread.Sleep(100);
						}
					} while (file == null && attempts >= 0);

					if (file != null)
					{
						ImportedElectionXml = XElement.Load(file);

						var rootName = ImportedElectionXml.Name.LocalName;

						if (rootName == "Election")
						{
							ImportSuccessful = true;
							ActivePath = FilePath;
						}
						else
						{
							ImportSuccessful = false;
							ErrorMessages.Add(string.Format("The specified file is not an Election XML file.\n\nContents start with: {1}\n\n{0}", FilePath, rootName));
							SourceExists = false;
						}

						file.Dispose();
					}
					else
					{
						throw new ApplicationException("Unknown error");
					}
				}
				catch (Exception ex)
				{
					ImportedElectionXml = null;
					ImportSuccessful = false;
					ErrorMessages.Add(string.Format("Error reading contents of the file ({0}).\n\n{1}", FilePath, ex.AllMessages()));
				}
			}

			return this;
		}

		public string ActivePath
		{
			get;
			private set;
		}

		public void RevertPathToActive()
		{
			FilePath = ActivePath;
		}
	}
}